package com.txc.common.global.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.txc.common.global.model.LoginUser;
import com.txc.common.utils.format.ObjectFormat;
import com.txc.common.utils.jwt.TokenManager;
import com.txc.common.utils.middleware.RedisUtils;
import com.txc.common.utils.supply.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;



import static com.txc.common.global.constant.StrConstant.AUTHORIZATION;

/**
 * 用户信息拦截器
 *
 * @ClassName: UserInfoInterceptor
 * @Author: TXC
 * @Date: 2023-08-08 22:44
 **/
public class UserInfoInterceptor implements HandlerInterceptor {
    private final RedisUtils redisUtils;
    private final TokenManager tokenManager;
    ;

    public UserInfoInterceptor(RedisUtils redisUtils, TokenManager tokenManager) {
        this.redisUtils = redisUtils;
        this.tokenManager = tokenManager;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(AUTHORIZATION);
        if (StrUtil.isNotBlank(token)) {
            String userId = tokenManager.getUserId(token);
            Object userInfo = redisUtils.get(tokenManager.getCacheKey() + userId);
            if (ObjectUtil.isNotNull(userInfo)) {
                LoginUser user = ObjectFormat.objToObject(userInfo, LoginUser.class);
                UserContext.setUser(user);
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        UserContext.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
